package org.springblade.modules.opcua.init;

import lombok.extern.slf4j.Slf4j;
import org.springblade.modules.opcua.config.OpcServerConfig;
import org.springblade.modules.opcua.action.ShardingManager;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ShardingRunner implements ApplicationRunner {
    @Resource
    private OpcServerConfig jhServerConfig;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    //作业
    private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);

    @Override
    public void run(ApplicationArguments args) throws Exception {
        scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                String pre = "opc:worker:";
                String worker = pre + jhServerConfig.getName();
                redisTemplate.opsForValue().set(worker, "Y", 12, TimeUnit.SECONDS);
                Set<String> keys = redisTemplate.keys(pre + "*");
                List<String> keyList = new ArrayList<>(keys);
                Collections.sort(keyList);
                int idx = 0;
                for (int i = 0; i < keyList.size(); i++) {
                    if (keyList.get(i).equals(worker)) {
                        idx = i;
                    }
                }
                ShardingManager.getSharding().setWorkerIdx(idx).setWorkerSize(keyList.size());
            }
        }, 3, 3, TimeUnit.SECONDS);
    }
}
